package com.cxl.controller;


import com.alibaba.fastjson.JSON;
import com.cxl.config.AjaxResult;
import com.cxl.entity.Fires;
import com.cxl.entity.LogDoc;
import com.cxl.es.EsRspository;
import com.cxl.feign.BaseFeign;
import com.cxl.morspository.MogoRspository;
import com.cxl.service.IFiresService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 崔学磊
 * @since 2022-03-16
 */
@RestController
@RequestMapping("/fires")
public class FiresController {

    @Autowired
    private IFiresService iFiresService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private EsRspository esRspository;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private BaseFeign baseFeign;

    /*es列表*/
    @PostMapping(value = "/list")
    public Page<Fires> eslist(@RequestBody Fires fires) {
        return iFiresService.findAll(fires);
    }

    /*es全量同步*/
    @GetMapping(value = "/eslist")
    public void eslist() {
        iFiresService.eslist();
    }

    //日志数据从mongodb中获取并且可以实现关键词搜索查询
    @GetMapping(value = "/loglist")
    public List<LogDoc> logDocList(LogDoc logDoc) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        if (StringUtils.isNoneBlank(logDoc.getContent())) {
            criteria.and("content").is(logDoc.getContent());
        }
        query.addCriteria(criteria);
        List<LogDoc> list = mongoTemplate.find(query, LogDoc.class);
        return list;
    }

    /*添加*/
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody Fires fires) {
        if (!redisTemplate.opsForValue().setIfAbsent(fires.toString(), null, 15, TimeUnit.SECONDS)) {
            return AjaxResult.err(500, "不可重复提交");
        }
        iFiresService.save(fires);
        fires = iFiresService.getFindOne(fires.getId());
        esRspository.save(fires);
        //添加成功后，通过kafka发送邮件到qq邮箱
        redisTemplate.opsForValue().set(JSON.toJSONString(fires), null);
        kafkaTemplate.send("test", "email", JSON.toJSONString(fires));
        return AjaxResult.ok();
    }


    //fegin远程调用
    @GetMapping(value = "/type")
    public List type() {
        return baseFeign.gettypelist();
    }
}
